# coding:utf-8
'''
Created on 2010-1-17

@author: Jason Green
@author-email: guileen@gmail.com
'''
from django.utils.encoding import smart_str
from djangosnippets.contrib.generic import modelhelper
from urllib import urlencode
try:
    basestring
except NameError:
    basestring = str, unicode

def link(value, field=None, ident=0):
    '''
    单个对象生成 一个链接，或html，也可以生成 ul,li的链接树
    @param value:
    @param field:
    @param ident: 对齐
    '''
    if field:
        v = modelhelper.get_deep_attr(value, field)
        object = v[0]
        value = v[1]
    else:
        object = None
        value = value

    if isinstance(value, basestring,) or not isinstance(value, (tuple, list, set)):
        if hasattr(value, 'get_absolute_url'):
            url = value.get_absolute_url()
        elif object and hasattr(object, 'get_absolute_url'):
            url = object.get_absolute_url()
        else:
            url = None

        if url:
            return '<a href="%s" >%s</a>' % (url, modelhelper.text(value))
        else:
            return modelhelper.text(value)

    sublist = ''
    ident_str = ' ' * ident
    for obj in value:
        sublist = '%s\n%s<li>%s</li>' % (sublist, ident_str, link(obj, None, ident + 4))
    return '<ul>%s</ul>' % sublist



def query(value, **kwargs):
    '''
    {{ query_dict|query_string(page=1) }}
    @param value:
    '''
    output = []
    if value:
        kwargs.update(value)
    for k, v in kwargs.items():
        if v:
            output.append(urlencode({smart_str(k, 'utf-8'): smart_str(v, 'utf-8')}))
    return '&'.join(output)


def list(object_list, fields=None, query_dict=None, order_by=None, callback=None):
    output = []
    if object_list:
        callback = callback or modelhelper.text
        obj = object_list[0]
        output.append('<table id="%s" class="listing"><thead><tr>' % modelhelper.name(obj))
        for f in fields or modelhelper.fields_of(obj, 'list'):
            if order_by == f:
                qs = query(query_dict, order_by='-' + f)
                order_type = " desc"
            elif order_by == '-' + f:
                qs = query(query_dict, order_by='')
                order_type = " asc"
            else:
                qs = query(query_dict, order_by=f)
                order_type = ""
            output.append('<th class="%s%s"><a href="?%s">%s</a></th>' % (f , order_type, qs, modelhelper.name(obj, f)))

        output.write('</tr></thead><tbody>')
        for index, obj in enumerate(object_list):
            output.append('<tr class="%s">' % index % 2 and 'even' or 'odd')
            url = hasattr(obj, 'get_absolute_url') and obj.get_absolute_url() or '#'
            for f in fields or modelhelper.fields_of(obj, 'list'):
                output.append('<td class="%s "><a href="%s">%s</a></td>' (f, url, callback(obj, f)))
            output.append('</tr>')
        output.append('</tbody></table>')
    return ''.join(output)

def detail(obj, fields=None):
    output = []
    for f in fields or modelhelper.fields_of(obj, 'detail'):
        output.append('<tr><th>%s</th><td>%s</td></tr>' % (modelhelper.name(obj, f), link(obj, f, False),))
    return ''.join(output)

def page_list(pages, page, page_prefix=None, page_callback=None, radius=2):
    '''
    分页显示的元素,包含，首页、...前2页,当前页,后2页...尾页, 省略号在被省略的页数大于等于2的时候出现，如1,...,3,4,<5>的情况不会出现
    1,2,<3>,4,5,...,20  ; 
    <1>,2,3,...,20 ; 
    1,2,3,4,<5>,6,7...,20 ; 
    1,...,6,7,<8>,9,10,...20 ; 
    1,.14,15,<16>,17,18,19,20;
    @param pages:
    @param page:
    @param page_prefix:
    @param page_callback:
    @param radius:
    '''
    page_callback = page_callback or (lambda p:'<a class="page-list-item" href="%s%s">%s</a>' % (page_prefix, p, p))
    items = []
    if page == 1:
        items.append('<strong class="current">1</strong>')
    else:
        items.append(page_callback(1))

    if page > 3 + radius:
        items.append('<span>...</span>')
        _from = page - radius
    else:
        _from = 2
    for p in range(_from, page):
        items.append(page_callback(p))
    if page > 1 and page < pages:
        items.append('<strong class="current">%d</strong>' % page)

    if page < pages - 3 - radius:
        _to = page + radius + 1
    else:
        _to = pages

    for p in range(page + 1, _to):
        items.append(page_callback(p))

    if pages > page:
        if page < pages - 3 - radius:
            items.append('<span>...</span>')

        if page == pages:
            items.append('<strong class="current">%d</strong>' % pages)
        else:
            items.append(page_callback(pages))

    return items

name = verbose_name = modelhelper.get_verbose_name
since_until = modelhelper.since_until

